/**
 * Created by Xxx on 2017/11/24.
 */
$(function(){
	$.fn.tonnnMenu = function(properties){
		var defaults = {
			show     : 'click',
			hide     : 'clickout',
			width    : 0,
			iconList :[],
			itmeList :[]
		};
		jQuery.extend(defaults,properties);

		//给当前项创建菜单名
		var menuId = 'menu' + Math.floor(Math.random()*1000);
		$(this).addClass('show' + menuId);

		//显示菜单
		this.on(defaults.show,function(){$('.' + menuId).show();});

		//菜单宽度
		var menuWidth;
		if(defaults.width == 0){
			menuWidth = $(this).outerWidth(true) - 2;
		}else{
			menuWidth = defaults.width;
		}

		//隐藏菜单
		if(defaults.hide == 'clickout'){
			$(document).click(function(){
				var e = e || window.event;
				var elem = e.target || e.srcElement;
				while (elem) {
					if (elem.className && (elem.className.indexOf(''+ menuId +'')>-1 || elem.className.indexOf('show'+ menuId +'')>-1)) {
						return;
					}
					elem = elem.parentNode;
				}
				$('.' + menuId).hide();
			});
		}else{
			$(document).on('mouseout',"." + menuId,function(){$('.' + menuId).hide();});
			$(document).on('mouseover',"." + menuId,function(){$('.' + menuId).show();});
			this.on('mouseout',function(){$('.' + menuId).hide();});
			this.on('mouseover',function(){$('.' + menuId).show();});
		}

		//创建菜单
		if($('.'+ menuId).length <= 0){
			var menuContent = '<ul>';
			var i=0;
			var icon='';
			$.each(defaults.itmeList,function(key,val){
				if(defaults.iconList[i]){
					icon = '<span class="'+ defaults.iconList[i] +' mr5"></span> ';
				}else{
					icon = '';
				}
				menuContent += '<li><a href="'+ val +'">'+ icon + key +'</a></li>';
				i++;
			});
			menuContent += '<div style="clear:both"></div></ul>';

			$(this).append('\
				<div class="'+ menuId +'" style="display:none; position:absolute; border:1px solid #ddd; background-color:#fff; z-index:999; box-shadow:0 0 3px #ccc;">\
					'+ menuContent +'\
				</div>\
			');

			$('.'+ menuId).css({'width':menuWidth,'left':$(this).offset().left,'top':$(this).offset().top + $(this).outerHeight(true)});
			$('.'+ menuId + ' ul li').css({'height':'36px','line-height':'36px','padding':'0 10px'});
			$('.'+ menuId + ' ul li a').css({'height':'36px','line-height':'36px','display':'block','font-size':'13px'});
		}

		$('.'+ menuId + ' ul li').mouseover(function(){$(this).css({'background-color':'#f8f8f8'});});
		$('.'+ menuId + ' ul li').mouseout(function(){$(this).css({'background-color':'#fff'});});

    };//End tonnnMenu
});